// 管理用户数据
import {defineStore} from 'pinia'
import {ref} from 'vue'
import {loginApi} from '@/apis/user.js'
import {mergeCartAPI} from '@/apis/cart.js'
import {useCartStore} from "@/stores/CartStore.js";

export const useUserStore = defineStore('user', () => {
        const cartStore = useCartStore()
        //1.定义store
        const userInfo = ref({})
        //2.定义action
        const getUserInfo = async ({account, password}) => {
            const res = await loginApi({account, password})
            userInfo.value = res.result

            // 调用合并购物车接口，将未登录时添加的购物车数据上传
            await mergeCartAPI(cartStore.cartList.map(item => {
                return {
                    skuId: item.skuId,
                    selected: item.selected,
                    count: item.count
                }
            }))
            await cartStore.updateCart()
        }
        const clearUserInfo = () => {
            userInfo.value = {}
            cartStore.clearCart()
        }

        //3.返回store 和 action
        return {userInfo, getUserInfo, clearUserInfo}
    },
    {
        // 持久化配置 存入ls
        persist: true,
    },)